<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>云存储管理系统 - 用户中心</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/layui@2.9.10/dist/css/layui.css">
    <style>
        body { background: #f5f5f7; }
        .layui-header.custom-header {
            background: #4A90E2;
            color: #fff;
            box-shadow: 0 2px 6px rgba(0,0,0,0.08);
            position: fixed;
            top: 0; left: 0; right: 0; z-index: 1001;
            height: 64px;
        }
        .custom-header .header-left {
            float: left;
            height: 64px;
            display: flex;
            align-items: center;
            font-size: 20px;
            font-weight: bold;
            letter-spacing: 2px;
            padding-left: 32px;
        }
        .custom-header .header-center {
            float: left;
            height: 64px;
            display: flex;
            align-items: center;
            justify-content: center;
            width: 100%;
            position: absolute;
            left: 0; right: 0;
            pointer-events: none;
        }
        .custom-header .search-wrap {
            width: 360px;
            margin: 0 auto;
            position: relative;
            pointer-events: all;
        }
        .custom-header .search-wrap .layui-input {
            border-radius: 18px;
            padding-left: 34px;
            background: rgba(255,255,255,0.2);
            border: 1px solid rgba(255,255,255,0.3);
            color: #fff;
        }
        .custom-header .search-wrap .layui-input::placeholder {
            color: rgba(255,255,255,0.7);
        }
        .custom-header .search-wrap .layui-icon-search {
            font-size: 22px;
            position: absolute;
            left: 12px;
            top: 10px;
            color: rgba(255,255,255,0.7);
        }
        .custom-header .header-right {
            float: right;
            height: 64px;
            display: flex;
            align-items: center;
            padding-right: 36px;
        }
        .custom-header .user-name {
            font-size: 16px;
            color: #fff;
            margin-right: 16px;
        }
        .custom-header .user-badge {
            background: rgba(255,255,255,0.2);
            color: #fff;
            padding: 2px 8px;
            border-radius: 8px;
            font-size: 12px;
            margin-right: 12px;
        }
        .custom-header .now-time {
            color: rgba(255,255,255,0.8);
            font-size: 14px;
            margin-right: 16px;
            margin-left: 12px;
        }
        .custom-header .logout-btn {
            background: #FF5722 !important;
            color: #fff !important;
            border-radius: 16px;
            margin-left: 8px;
            padding: 0 16px;
        }
        .layui-side.custom-side {
            top: 64px;
            background: #5A9FD4 !important;
            width: 200px;
            color: #fff;
        }
        .layui-nav.custom-nav .layui-nav-item > a {
            color: rgba(255,255,255,0.9);
            font-size: 16px;
        }
        .layui-nav.custom-nav .layui-nav-child a {
            color: #fff !important;
            font-size: 15px;
        }
        .layui-nav.custom-nav .layui-nav-itemed > a,
        .layui-nav.custom-nav .layui-this > a {
            background: #3A7BC8 !important;
            color: #fff !important;
        }
        .layui-nav.custom-nav .layui-nav-child dd.layui-this a {
            background: #2E5E95 !important;
            color: #fff !important;
        }
        .custom-main {
            margin-left: 200px;
            margin-top: 80px;
            padding: 32px 32px 32px 32px;
            min-height: 600px;
        }
        .layui-card {margin-bottom: 16px;}
        .layui-table-view {margin-bottom: 0;}
        .layui-badge {font-size: 13px;}
        .upload-card {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 32px;
            border-radius: 8px;
            text-align: center;
            margin-bottom: 24px;
            cursor: pointer;
            transition: transform 0.2s;
        }
        .upload-card:hover {
            transform: translateY(-2px);
        }
        .upload-icon {
            font-size: 48px;
            margin-bottom: 16px;
        }
        .storage-info {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 16px;
            margin-bottom: 24px;
        }
        .storage-item {
            background: white;
            padding: 24px;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            text-align: center;
        }
        .storage-number {
            font-size: 24px;
            font-weight: bold;
            color: #4A90E2;
            margin-bottom: 8px;
        }
        .storage-label {
            color: #666;
            font-size: 14px;
        }
    </style>
</head>
<body class="layui-layout-body">

<!-- 顶部栏 -->
<div class="layui-header custom-header">
    <div class="header-left">
        <span>我的云存储</span>
    </div>
    <div class="header-center">
        <div class="search-wrap">
            <i class="layui-icon layui-icon-search"></i>
            <input type="text" name="fileSearch" id="search-input" placeholder="搜索我的文件..." autocomplete="off" class="layui-input" style="width: 100%;">
        </div>
    </div>
    <div class="header-right">
        <span class="now-time" id="now-time"></span>
        <span class="user-badge">普通用户</span>
        <span class="user-name" id="user-name">用户</span>
        <button class="layui-btn logout-btn" id="btn-logout">退出</button>
    </div>
    <div style="clear: both;"></div>
</div>

<!-- 侧边栏 -->
<div class="layui-side custom-side">
    <div class="layui-side-scroll">
        <ul class="layui-nav layui-nav-tree custom-nav" lay-filter="user-side">
            <li class="layui-nav-item layui-nav-itemed">
                <a href="javascript:;">我的文件</a>
                <dl class="layui-nav-child">
                    <dd class="layui-this"><a href="javascript:;" id="btn-my-files">所有文件</a></dd>
                    <dd><a href="javascript:;" id="btn-recent-files">最近使用</a></dd>
                    <dd><a href="javascript:;" id="btn-trash">回收站</a></dd>
                </dl>
            </li>
            <li class="layui-nav-item">
                <a href="javascript:;" id="btn-upload">文件上传</a>
            </li>
            <li class="layui-nav-item">
                <a href="javascript:;" id="btn-profile">个人信息</a>
            </li>
        </ul>
    </div>
</div>

<!-- 主体内容区 -->
<div class="custom-main" id="main-container">
    <div id="file-panel"></div>
</div>

<script src="https://cdn.jsdelivr.net/npm/layui@2.9.10/dist/layui.js"></script>
<script>
    layui.use(['element','layer','table','upload','form'], function(){
        var $ = layui.jquery, element = layui.element, layer = layui.layer, table = layui.table, upload = layui.upload, form = layui.form;

        // 真实数据，通过API获取
        var userFiles = [];
        var storageInfo = {
            totalFiles: 0,
            totalStorage: "0MB",
            usedStorage: "0MB",
            storageUsage: 0
        };

        // 获取JWT Token
        function getToken() {
            const localToken = localStorage.getItem('token');
            const sessionToken = sessionStorage.getItem('token');
            console.log('检查token - localStorage:', localToken ? '有值' : '无值', 'sessionStorage:', sessionToken ? '有值' : '无值');
            return localToken || sessionToken;
        }

        // 格式化文件大小
        function formatFileSize(bytes) {
            if (bytes === 0) return '0B';
            const k = 1024;
            const sizes = ['B', 'KB', 'MB', 'GB'];
            const i = Math.floor(Math.log(bytes) / Math.log(k));
            return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + sizes[i];
        }

        // 获取存储统计信息
        function loadStorageStats() {
            const token = getToken();
            if (!token) {
                console.log('Token not found, skipping stats load');
                return;
            }

            $.ajax({
                url: '/api/files/stats',
                type: 'GET',
                headers: {
                    'Authorization': 'Bearer ' + token
                },
                success: function(res) {
                    if (res.success) {
                        const stats = res.data;
                        storageInfo = {
                            totalFiles: stats.totalFiles,
                            totalStorage: formatFileSize(stats.totalSize + 2147483648), // 假设总容量为当前使用+2GB
                            usedStorage: formatFileSize(stats.totalSize),
                            storageUsage: Math.round((stats.totalSize / (stats.totalSize + 2147483648)) * 100)
                        };
                        renderMyFiles(); // 重新渲染页面显示最新数据
                    }
                },
                error: function(xhr, status, error) {
                    console.log('获取存储统计信息失败:', error, 'status:', xhr.status);
                    if (xhr.status === 401) {
                        console.log('401错误，认证失败，token可能无效');
                        // 清除无效token
                        localStorage.removeItem('token');
                        sessionStorage.removeItem('token');
                        // 未认证，重定向到登录页面
                        window.location.href = '/auth/user-login';
                    }
                }
            });
        }

        // 获取用户文件列表
        function loadUserFiles() {
            const token = getToken();
            if (!token) {
                console.log('Token not found, skipping files load');
                return;
            }

            $.ajax({
                url: '/api/files/list',
                type: 'GET',
                headers: {
                    'Authorization': 'Bearer ' + token
                },
                success: function(res) {
                    if (res.success) {
                        userFiles = res.data.map(file => ({
                            id: file.fileId,
                            name: file.originalFilename,
                            type: getFileTypeDisplay(file.fileExtension),
                            size: formatFileSize(file.fileSize),
                            time: formatDateTime(file.updatedAt),
                            encrypted: file.encrypted
                        }));
                        renderMyFiles(); // 重新渲染页面
                    }
                },
                error: function(xhr, status, error) {
                    console.log('获取文件列表失败:', error, 'status:', xhr.status);
                    if (xhr.status === 401) {
                        console.log('401错误，认证失败，token可能无效');
                        // 清除无效token
                        localStorage.removeItem('token');
                        sessionStorage.removeItem('token');
                        // 未认证，重定向到登录页面
                        window.location.href = '/auth/user-login';
                    } else {
                        // 其他错误才显示提示消息，避免初次加载时的误报
                        console.warn('文件列表加载失败，可能是新用户没有文件');
                    }
                }
            });
        }

        // 获取文件类型显示名称
        function getFileTypeDisplay(extension) {
            const types = {
                'pdf': '文档', 'doc': '文档', 'docx': '文档', 'txt': '文档',
                'jpg': '图片', 'jpeg': '图片', 'png': '图片', 'gif': '图片',
                'mp4': '视频', 'avi': '视频', 'mov': '视频',
                'mp3': '音频', 'wav': '音频', 'flac': '音频'
            };
            return types[extension?.toLowerCase()] || '其他';
        }

        // 格式化日期时间
        function formatDateTime(dateTime) {
            if (!dateTime) return '';
            const date = new Date(dateTime);
            return date.getFullYear() + '-' + 
                   String(date.getMonth() + 1).padStart(2, '0') + '-' + 
                   String(date.getDate()).padStart(2, '0') + ' ' +
                   String(date.getHours()).padStart(2, '0') + ':' + 
                   String(date.getMinutes()).padStart(2, '0') + ':' + 
                   String(date.getSeconds()).padStart(2, '0');
        }

        function updateTime(){
            var now = new Date();
            var str = now.getFullYear()+'-'+
                ('0'+(now.getMonth()+1)).slice(-2)+'-'+
                ('0'+now.getDate()).slice(-2)+' '+
                ('0'+now.getHours()).slice(-2)+':'+
                ('0'+now.getMinutes()).slice(-2)+':'+
                ('0'+now.getSeconds()).slice(-2);
            document.getElementById("now-time").innerText = str;
        }
        updateTime(); setInterval(updateTime, 1000);

        // 页面初始化 - 加载真实数据
        // 简化token检查，给更多时间让token存储完成
        function initializeData() {
            const token = getToken();
            console.log('初始化检查token:', token ? '存在' : '不存在');
            
            if (token) {
                // token已存在，立即加载数据
                console.log('Token存在，开始加载数据');
                loadStorageStats();
                loadUserFiles();
            } else {
                // 延迟一段时间再检查，给localStorage更多时间
                console.log('Token不存在，500ms后重试');
                setTimeout(function() {
                    const tokenRetry = getToken();
                    console.log('重试检查token:', tokenRetry ? '存在' : '不存在');
                    
                    if (tokenRetry) {
                        console.log('重试成功，开始加载数据');
                        loadStorageStats();
                        loadUserFiles();
                    } else {
                        console.log('重试失败，可能需要重新登录');
                        // 不立即跳转，给用户一些提示
                        layer.msg('登录状态已过期，请重新登录', {icon: 2, time: 2000}, function() {
                            window.location.href = '/auth/user-login';
                        });
                    }
                }, 500);
            }
        }
        
        initializeData();

        // 顶部搜索
        $('#search-input').on('keydown', function(e){
            if(e.keyCode === 13){
                var val = $(this).val();
                if(val.trim()) {
                    searchFiles(val);
                } else {
                    renderMyFiles();
                }
                return false;
            }
        });

        // 菜单切换
        $('#btn-my-files').click(function(){
            setActiveMenu(this);
            renderMyFiles();
        });
        $('#btn-recent-files').click(function(){
            setActiveMenu(this);
            renderRecentFiles();
        });
        $('#btn-trash').click(function(){
            setActiveMenu(this);
            renderTrash();
        });
        $('#btn-upload').click(function(){
            setActiveMenu(this);
            renderUploadPage();
        });
        $('#btn-profile').click(function(){
            setActiveMenu(this);
            renderProfile();
        });

        $('#btn-logout').click(function(){
            layer.confirm('确定要退出吗？', {icon: 3, title:'提示'}, function(index){
                window.location.href = '/auth/user-login';
                layer.close(index);
            });
        });

        function setActiveMenu(element) {
            $('.layui-nav-child dd').removeClass('layui-this');
            $('.layui-nav-item').removeClass('layui-this');
            $(element).parent().addClass('layui-this');
            $(element).closest('.layui-nav-item').addClass('layui-nav-itemed');
        }

        // 我的文件
        function renderMyFiles(){
            var rows = '';
            for(var i=0;i<userFiles.length;i++){
                var f = userFiles[i];
                var encryptIcon = f.encrypted ? '<i class="layui-icon layui-icon-password" style="color: #FF5722;"></i> ' : '';
                rows += `<tr>
                <td>${encryptIcon}${f.name}</td>
                <td>${f.type}</td>
                <td>${f.size}</td>
                <td>${f.time}</td>
                <td>
                    <button class="layui-btn layui-btn-xs layui-btn-primary btn-download" data-id="${f.id}" data-name="${f.name}">下载</button>
                    <button class="layui-btn layui-btn-xs layui-btn-danger btn-del" data-id="${f.id}" data-idx="${i}" data-name="${f.name}">删除</button>
                </td>
            </tr>`;
            }

            $('#main-container').html(`
        <div class="storage-info">
            <div class="storage-item">
                <div class="storage-number">${storageInfo.totalFiles}</div>
                <div class="storage-label">文件总数</div>
            </div>
            <div class="storage-item">
                <div class="storage-number">${storageInfo.usedStorage}</div>
                <div class="storage-label">已用空间</div>
            </div>
            <div class="storage-item">
                <div class="storage-number">${storageInfo.totalStorage}</div>
                <div class="storage-label">总容量</div>
            </div>
            <div class="storage-item">
                <div class="storage-number">${storageInfo.storageUsage}%</div>
                <div class="storage-label">使用率</div>
            </div>
        </div>
        
        <div class="layui-card">
            <div class="layui-card-header">
                我的文件
                <button class="layui-btn layui-btn-sm layui-btn-normal" id="btn-quick-upload" style="float:right;">
                    <i class="layui-icon layui-icon-upload"></i> 快速上传
                </button>
            </div>
            <div class="layui-card-body">
                <table class="layui-table" lay-size="sm">
                    <thead>
                        <tr>
                            <th>文件名</th>
                            <th>类型</th>
                            <th>大小</th>
                            <th>修改时间</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody id="file-table-body">${rows}</tbody>
                </table>
            </div>
        </div>
        `);

            bindFileActions();
        }

        // 文件上传页面
        function renderUploadPage(){
            $('#main-container').html(`
        <div class="upload-card" id="upload-area">
            <div class="upload-icon">
                <i class="layui-icon layui-icon-upload-circle"></i>
            </div>
            <h3>点击或拖拽文件到此处上传</h3>
            <p>支持多种格式：文档、图片、音频、视频等</p>
        </div>
        
        <div class="layui-card">
            <div class="layui-card-header">上传设置</div>
            <div class="layui-card-body">
                <form class="layui-form">
                    <div class="layui-form-item">
                        <label class="layui-form-label">文件加密</label>
                        <div class="layui-input-block">
                            <input type="checkbox" name="encrypt" id="upload-encrypt" lay-skin="switch" lay-text="启用|禁用">
                        </div>
                    </div>
                    <div class="layui-form-item" id="password-item" style="display:none;">
                        <label class="layui-form-label">加密密码</label>
                        <div class="layui-input-block">
                            <input type="password" name="password" placeholder="请设置加密密码" class="layui-input">
                        </div>
                    </div>
                </form>
            </div>
        </div>
        `);

            form.render();
            
            // 加密开关监听
            form.on('switch()', function(data){
                if(data.elem.checked){
                    $('#password-item').show();
                } else {
                    $('#password-item').hide();
                }
            });

            // 文件上传功能
            upload.render({
                elem: '#upload-area',
                url: '/api/files/upload',
                headers: {
                    'Authorization': 'Bearer ' + getToken()
                },
                accept: 'file',
                multiple: true,
                before: function(obj){
                    layer.load(); // 显示加载中
                },
                done: function(res){
                    layer.closeAll('loading'); // 关闭加载
                    if(res.success){
                        layer.msg('文件上传成功！', {icon: 1});
                        // 刷新文件列表和存储统计
                        loadUserFiles();
                        loadStorageStats();
                    } else {
                        layer.msg('上传失败：' + res.message, {icon: 2});
                    }
                },
                error: function(){
                    layer.closeAll('loading');
                    layer.msg('上传失败，请重试', {icon: 2});
                }
            });
        }

        // 个人信息
        function renderProfile(){
            // 先显示加载中的占位内容
            $('#main-container').html(`
        <div class="layui-card">
            <div class="layui-card-header">个人信息</div>
            <div class="layui-card-body">
                <div style="text-align: center; padding: 40px;">
                    <i class="layui-icon layui-icon-loading layui-anim layui-anim-rotate layui-anim-loop" style="font-size: 30px;"></i>
                    <p>加载中...</p>
                </div>
            </div>
        </div>
        `);

            // 获取用户信息
            loadUserProfile();
        }

        // 加载用户信息
        function loadUserProfile() {
            const token = getToken();
            if (!token) {
                layer.msg('请先登录', {icon: 2});
                window.location.href = '/auth/user-login';
                return;
            }

            $.ajax({
                url: '/api/users/profile',
                type: 'GET',
                headers: {
                    'Authorization': 'Bearer ' + token
                },
                success: function(res) {
                    if (res.success) {
                        const userInfo = res.data;
                        renderUserProfileForm(userInfo);
                    } else {
                        layer.msg('获取用户信息失败', {icon: 2});
                    }
                },
                error: function(xhr, status, error) {
                    console.log('获取用户信息失败:', error);
                    if (xhr.status === 401) {
                        window.location.href = '/auth/user-login';
                    } else {
                        layer.msg('获取用户信息失败', {icon: 2});
                    }
                }
            });
        }

        // 渲染用户信息表单
        function renderUserProfileForm(userInfo) {
            console.log('renderUserProfileForm 接收到的 userInfo:', userInfo);
            console.log('userInfo.email:', userInfo ? userInfo.email : 'userInfo is undefined');
            
            $('#main-container').html(`
        <div class="layui-card">
            <div class="layui-card-header">个人信息</div>
            <div class="layui-card-body">
                <form class="layui-form" lay-filter="profile-form">
                    <div class="layui-form-item">
                        <label class="layui-form-label">用户名</label>
                        <div class="layui-input-block">
                            <input type="text" name="username" value="${userInfo ? userInfo.username : ''}" disabled class="layui-input layui-disabled">
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label">邮箱</label>
                        <div class="layui-input-block">
                            <input type="email" name="email" value="${userInfo ? (userInfo.email || '') : ''}" class="layui-input">
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label">注册时间</label>
                        <div class="layui-input-block">
                            <input type="text" value="${userInfo ? formatDateTime(userInfo.createdAt) : ''}" disabled class="layui-input layui-disabled">
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label">存储配额</label>
                        <div class="layui-input-block">
                            <input type="text" value="5GB" disabled class="layui-input layui-disabled">
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <div class="layui-input-block">
                            <button class="layui-btn" lay-submit>保存修改</button>
                            <button type="button" class="layui-btn layui-btn-normal" id="btn-change-password">修改密码</button>
                        </div>
                    </div>
                </form>
            </div>
        </div>
        `);

            form.render();
            
            // 添加调试信息：检查表单渲染后的值
            console.log('表单渲染后的邮箱输入框值:', $('input[name="email"]').val());
            console.log('表单渲染后的用户名输入框值:', $('input[name="username"]').val());
            
            // 保存修改按钮事件处理
            form.on('submit(profile-form)', function(data){
                const token = getToken();
                if (!token) {
                    layer.msg('请先登录', {icon: 2});
                    return false;
                }
                
                // 直接从DOM获取邮箱值，而不依赖Layui的data.field
                const emailValue = $('input[name="email"]').val();
                
                const loadingIndex = layer.load(1);
                
                // 添加调试日志
                console.log('提交的表单数据:', data.field);
                console.log('从DOM获取的邮箱值:', emailValue);
                console.log('发送的邮箱:', emailValue);
                console.log('使用的token:', token);
                console.log('所有表单字段:', Object.keys(data.field));
                console.log('email字段是否存在:', 'email' in data.field);
                
                $.ajax({
                    url: '/api/users/profile',
                    type: 'PUT',
                    headers: {
                        'Authorization': 'Bearer ' + token,
                        'Content-Type': 'application/json'
                    },
                    data: JSON.stringify({
                        email: emailValue
                    }),
                    success: function(res) {
                        layer.close(loadingIndex);
                        if (res.success) {
                            layer.msg('个人信息更新成功', {icon: 1});
                            // 重新渲染个人信息表单以显示更新后的数据
                            setTimeout(function() {
                                loadUserProfile();
                            }, 1000);
                        } else {
                            layer.msg(res.message || '更新失败', {icon: 2});
                        }
                    },
                    error: function(xhr) {
                        layer.close(loadingIndex);
                        console.error('更新个人信息失败:', xhr);
                        layer.msg('网络错误，请稍后再试', {icon: 2});
                    }
                });
                
                return false; // 阻止表单默认提交
            });
            
            // 修改密码按钮事件处理
            $('#btn-change-password').click(function(){
                showChangePasswordDialog();
            });
        }

        // 显示修改密码对话框
        function showChangePasswordDialog() {
            const token = getToken();
            if (!token) {
                layer.msg('请先登录', {icon: 2});
                return;
            }
            
            layer.open({
                type: 1,
                title: '修改密码',
                area: ['450px', '350px'],
                content: `
                    <div style="padding: 20px;">
                        <form class="layui-form" lay-filter="change-password-form">
                            <div class="layui-form-item">
                                <label class="layui-form-label">当前密码</label>
                                <div class="layui-input-block">
                                    <input type="password" name="currentPassword" required lay-verify="required" placeholder="请输入当前密码" autocomplete="off" class="layui-input">
                                </div>
                            </div>
                            <div class="layui-form-item">
                                <label class="layui-form-label">新密码</label>
                                <div class="layui-input-block">
                                    <input type="password" name="newPassword" required lay-verify="required|password" placeholder="请输入新密码（至少6位）" autocomplete="off" class="layui-input">
                                </div>
                            </div>
                            <div class="layui-form-item">
                                <label class="layui-form-label">确认密码</label>
                                <div class="layui-input-block">
                                    <input type="password" name="confirmPassword" required lay-verify="required|confirmPassword" placeholder="请确认新密码" autocomplete="off" class="layui-input">
                                </div>
                            </div>
                            <div class="layui-form-item">
                                <div class="layui-input-block">
                                    <button class="layui-btn" lay-submit lay-filter="change-password-submit">确认修改</button>
                                    <button type="button" class="layui-btn layui-btn-primary" onclick="layer.closeAll()">取消</button>
                                </div>
                            </div>
                        </form>
                    </div>
                `,
                success: function(layero, index) {
                    // 渲染表单
                    form.render();
                    
                    // 自定义验证规则
                    form.verify({
                        password: function(value) {
                            if (value.length < 6) {
                                return '密码长度不能少于6位';
                            }
                        },
                        confirmPassword: function(value) {
                            const newPassword = $('input[name="newPassword"]').val();
                            if (value !== newPassword) {
                                return '两次输入的密码不一致';
                            }
                        }
                    });
                    
                    // 表单提交处理
                    form.on('submit(change-password-submit)', function(data) {
                        const loadingIndex = layer.load(1);
                        
                        $.ajax({
                            url: '/api/users/change-password',
                            type: 'PUT',
                            headers: {
                                'Authorization': 'Bearer ' + token,
                                'Content-Type': 'application/json'
                            },
                            data: JSON.stringify({
                                currentPassword: data.field.currentPassword,
                                newPassword: data.field.newPassword,
                                confirmPassword: data.field.confirmPassword
                            }),
                            success: function(res) {
                                layer.close(loadingIndex);
                                if (res.success) {
                                    layer.msg('密码修改成功，请重新登录', {icon: 1, time: 2000}, function() {
                                        layer.closeAll();
                                        // 清除token，跳转到登录页
                                        localStorage.removeItem('token');
                                        window.location.href = '/auth/user-login';
                                    });
                                } else {
                                    layer.msg(res.message || '密码修改失败', {icon: 2});
                                }
                            },
                            error: function(xhr) {
                                layer.close(loadingIndex);
                                console.error('修改密码失败:', xhr);
                                layer.msg('网络错误，请稍后再试', {icon: 2});
                            }
                        });
                        
                        return false;
                    });
                }
            });
        }

        // 回收站
        function renderTrash(){
            // 先显示加载状态
            $('#main-container').html(`
        <div class="layui-card">
            <div class="layui-card-header">回收站</div>
            <div class="layui-card-body">
                <div style="text-align: center; padding: 40px;">
                    <i class="layui-icon layui-icon-loading layui-anim layui-anim-rotate layui-anim-loop" style="font-size: 30px;"></i>
                    <p>加载中...</p>
                </div>
            </div>
        </div>
        `);

            // 加载回收站文件
            loadTrashFiles();
        }

        // 加载回收站文件
        function loadTrashFiles() {
            const token = getToken();
            if (!token) {
                console.log('Token not found, skipping trash load');
                return;
            }

            $.ajax({
                url: '/api/files/list?includeDeleted=true',
                type: 'GET',
                headers: {
                    'Authorization': 'Bearer ' + token
                },
                success: function(res) {
                    if (res.success) {
                        // 过滤出已删除的文件
                        const deletedFiles = res.data.filter(file => file.isDeleted);
                        renderTrashTable(deletedFiles);
                    } else {
                        layer.msg('获取回收站文件失败', {icon: 2});
                    }
                },
                error: function(xhr, status, error) {
                    console.log('获取回收站文件失败:', error, 'status:', xhr.status);
                    if (xhr.status === 401) {
                        console.log('401错误，认证失败，token可能无效');
                        localStorage.removeItem('token');
                        sessionStorage.removeItem('token');
                        window.location.href = '/auth/user-login';
                    } else {
                        layer.msg('获取回收站文件失败', {icon: 2});
                    }
                }
            });
        }

        // 渲染回收站表格
        function renderTrashTable(deletedFiles) {
            let rows = '';
            
            if (deletedFiles.length === 0) {
                rows = '<tr><td colspan="4" style="text-align: center; color: #999;">回收站为空</td></tr>';
            } else {
                for (let i = 0; i < deletedFiles.length; i++) {
                    const file = deletedFiles[i];
                    const deleteTime = formatDateTime(file.deletedAt || file.updatedAt);
                    const encryptIcon = file.encrypted ? '<i class="layui-icon layui-icon-password" style="color: #FF5722;"></i> ' : '';
                    
                    // 计算保留期限（假设30天保留期）
                    const deleteDate = new Date(file.deletedAt || file.updatedAt);
                    const expireDate = new Date(deleteDate.getTime() + 30 * 24 * 60 * 60 * 1000);
                    const now = new Date();
                    const daysLeft = Math.ceil((expireDate - now) / (24 * 60 * 60 * 1000));
                    const expireText = daysLeft > 0 ? `${daysLeft}天后永久删除` : '即将永久删除';
                    
                    rows += `<tr>
                        <td>${encryptIcon}${file.originalFilename}</td>
                        <td>${deleteTime}</td>
                        <td>${expireText}</td>
                        <td>
                            <button class="layui-btn layui-btn-xs layui-btn-normal btn-restore" data-file-id="${file.fileId}">恢复</button>
                            <button class="layui-btn layui-btn-xs layui-btn-danger btn-permanent-delete" data-file-id="${file.fileId}">永久删除</button>
                        </td>
                    </tr>`;
                }
            }

            $('#main-container').html(`
        <div class="layui-card">
            <div class="layui-card-header">
                回收站
                <span style="color: #999; font-size: 12px; float: right;">文件在回收站中保留30天</span>
            </div>
            <div class="layui-card-body">
                <table class="layui-table" lay-size="sm">
                    <thead>
                        <tr>
                            <th>文件名</th>
                            <th>删除时间</th>
                            <th>保留期限</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody id="trash-table-body">${rows}</tbody>
                </table>
            </div>
        </div>
        `);

            bindTrashActions();
        }

        // 绑定回收站操作事件
        function bindTrashActions() {
            // 恢复文件
            $('.btn-restore').click(function() {
                const fileId = $(this).attr('data-file-id');
                const fileName = $(this).closest('tr').find('td:first').text();
                
                layer.confirm(`确定要恢复文件 "${fileName}" 吗？`, {icon: 3, title:'确认恢复'}, function(index) {
                    restoreFile(fileId);
                    layer.close(index);
                });
            });

            // 永久删除文件
            $('.btn-permanent-delete').click(function() {
                const fileId = $(this).attr('data-file-id');
                const fileName = $(this).closest('tr').find('td:first').text();
                
                layer.confirm(`确定要永久删除文件 "${fileName}" 吗？此操作不可撤销！`, {icon: 2, title:'确认永久删除'}, function(index) {
                    permanentDeleteFile(fileId);
                    layer.close(index);
                });
            });
        }

        // 恢复文件
        function restoreFile(fileId) {
            const token = getToken();
            if (!token) {
                layer.msg('请先登录', {icon: 2});
                return;
            }

            $.ajax({
                url: `/api/files/${fileId}/restore`,
                type: 'POST',
                headers: {
                    'Authorization': 'Bearer ' + token
                },
                success: function(res) {
                    if (res.success) {
                        layer.msg('文件恢复成功', {icon: 1});
                        loadTrashFiles(); // 重新加载回收站
                    } else {
                        layer.msg('文件恢复失败: ' + res.message, {icon: 2});
                    }
                },
                error: function() {
                    layer.msg('文件恢复失败', {icon: 2});
                }
            });
        }

        // 永久删除文件
        function permanentDeleteFile(fileId) {
            const token = getToken();
            if (!token) {
                layer.msg('请先登录', {icon: 2});
                return;
            }

            $.ajax({
                url: `/api/files/${fileId}?permanent=true`,
                type: 'DELETE',
                headers: {
                    'Authorization': 'Bearer ' + token
                },
                success: function(res) {
                    if (res.success) {
                        layer.msg('文件已永久删除', {icon: 1});
                        loadTrashFiles(); // 重新加载回收站
                    } else {
                        layer.msg('永久删除失败: ' + res.message, {icon: 2});
                    }
                },
                error: function() {
                    layer.msg('永久删除失败', {icon: 2});
                }
            });
        }

        // 最近文件
        function renderRecentFiles(){
            var recentFiles = userFiles.slice(-2); // 最近2个文件
            var rows = '';
            for(var i=0;i<recentFiles.length;i++){
                var f = recentFiles[i];
                var encryptIcon = f.encrypted ? '<i class="layui-icon layui-icon-password" style="color: #FF5722;"></i> ' : '';
                rows += `<tr>
                <td>${encryptIcon}${f.name}</td>
                <td>${f.type}</td>
                <td>${f.size}</td>
                <td>${f.time}</td>
                <td>
                    <button class="layui-btn layui-btn-xs layui-btn-primary">下载</button>
                </td>
            </tr>`;
            }

            $('#main-container').html(`
        <div class="layui-card">
            <div class="layui-card-header">最近使用的文件</div>
            <div class="layui-card-body">
                <table class="layui-table" lay-size="sm">
                    <thead>
                        <tr>
                            <th>文件名</th>
                            <th>类型</th>
                            <th>大小</th>
                            <th>最后访问</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody>${rows}</tbody>
                </table>
            </div>
        </div>
        `);
        }

        // 搜索文件
        function searchFiles(keyword){
            var filteredFiles = userFiles.filter(function(file){
                return file.name.toLowerCase().includes(keyword.toLowerCase());
            });

            var rows = '';
            for(var i=0;i<filteredFiles.length;i++){
                var f = filteredFiles[i];
                var encryptIcon = f.encrypted ? '<i class="layui-icon layui-icon-password" style="color: #FF5722;"></i> ' : '';
                rows += `<tr>
                <td>${encryptIcon}${f.name}</td>
                <td>${f.type}</td>
                <td>${f.size}</td>
                <td>${f.time}</td>
                <td>
                    <button class="layui-btn layui-btn-xs layui-btn-primary">下载</button>
                </td>
            </tr>`;
            }

            $('#main-container').html(`
        <div class="layui-card">
            <div class="layui-card-header">搜索结果："${keyword}" (${filteredFiles.length}个文件)</div>
            <div class="layui-card-body">
                <table class="layui-table" lay-size="sm">
                    <thead>
                        <tr>
                            <th>文件名</th>
                            <th>类型</th>
                            <th>大小</th>
                            <th>修改时间</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody>${rows}</tbody>
                </table>
            </div>
        </div>
        `);
        }

        // 绑定文件操作事件
        function bindFileActions(){
            $('#btn-quick-upload').click(function(){
                renderUploadPage();
            });

            $('.btn-download').click(function(){
                var fileId = $(this).attr('data-id');
                var fileName = $(this).attr('data-name');
                
                if (!fileId) {
                    layer.msg('文件ID不存在，无法下载', {icon: 2});
                    return;
                }
                
                var token = getToken();
                if (!token) {
                    layer.msg('请先登录', {icon: 2});
                    return;
                }
                
                // 显示下载中提示
                var loadingIndex = layer.load(1, { shade: [0.1, '#000'] });
                
                // 创建隐藏的下载链接
                var downloadUrl = '/api/files/download/' + fileId;
                var link = document.createElement('a');
                link.style.display = 'none';
                link.href = downloadUrl;
                link.download = fileName;
                
                // 设置请求头（通过fetch处理）
                fetch(downloadUrl, {
                    method: 'GET',
                    headers: {
                        'Authorization': 'Bearer ' + token
                    }
                })
                .then(response => {
                    layer.close(loadingIndex);
                    if (response.ok) {
                        return response.blob();
                    } else if (response.status === 401) {
                        throw new Error('认证失败，请重新登录');
                    } else if (response.status === 404) {
                        throw new Error('文件不存在');
                    } else {
                        throw new Error('下载失败：' + response.status);
                    }
                })
                .then(blob => {
                    // 创建下载链接并触发下载
                    var url = window.URL.createObjectURL(blob);
                    var a = document.createElement('a');
                    a.style.display = 'none';
                    a.href = url;
                    a.download = fileName;
                    document.body.appendChild(a);
                    a.click();
                    window.URL.revokeObjectURL(url);
                    document.body.removeChild(a);
                    
                    layer.msg('下载成功：' + fileName, {icon: 1});
                })
                .catch(error => {
                    layer.close(loadingIndex);
                    layer.msg('下载失败：' + error.message, {icon: 2});
                    console.error('Download error:', error);
                });
            });


            $('.btn-del').click(function(){
                var fileId = $(this).attr('data-id');
                var fileName = $(this).attr('data-name');
                var idx = $(this).attr('data-idx');
                
                if (!fileId) {
                    layer.msg('文件ID不存在，无法删除', {icon: 2});
                    return;
                }
                
                layer.confirm('确定要删除该文件吗？文件将移至回收站。', {icon: 3, title:'确认删除'}, function(confirmIndex){
                    var token = getToken();
                    if (!token) {
                        layer.msg('请先登录', {icon: 2});
                        return;
                    }
                    
                    // 显示删除中提示
                    var loadingIndex = layer.load(1, { shade: [0.1, '#000'] });
                    
                    // 调用删除API
                    $.ajax({
                        url: '/api/files/' + fileId,
                        type: 'DELETE',
                        headers: {
                            'Authorization': 'Bearer ' + token
                        },
                        success: function(res) {
                            layer.close(loadingIndex);
                            layer.close(confirmIndex);
                            
                            if (res.success) {
                                // 从本地数组中移除文件
                                userFiles.splice(idx, 1);
                                renderMyFiles();
                                layer.msg('文件已移至回收站：' + fileName, {icon: 1});
                            } else {
                                layer.msg('删除失败：' + (res.message || '未知错误'), {icon: 2});
                            }
                        },
                        error: function(xhr, status, error) {
                            layer.close(loadingIndex);
                            layer.close(confirmIndex);
                            
                            if (xhr.status === 401) {
                                layer.msg('认证失败，请重新登录', {icon: 2});
                                // 清除无效token
                                localStorage.removeItem('token');
                                sessionStorage.removeItem('token');
                                window.location.href = '/auth/user-login';
                            } else if (xhr.status === 404) {
                                layer.msg('文件不存在', {icon: 2});
                            } else {
                                layer.msg('删除失败：' + error, {icon: 2});
                            }
                            console.error('Delete error:', error, 'status:', xhr.status);
                        }
                    });
                });
            });
        }
    });
</script>
</body>
</html>